"""
房间管理路由
"""
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from utils import ApiResponse
from services.room_service import RoomService

api_bp = Blueprint('room', __name__, url_prefix='/admin')
room_service = RoomService()


@api_bp.route('/rooms', methods=['GET'])
@jwt_required()
def get_rooms():
    """获取房间列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '').strip()
        room_type_id = request.args.get('room_type_id', type=int)
        room_status_id = request.args.get('room_status_id', type=int)
        
        data = room_service.get_rooms_paginated_dto(
            page=page,
            per_page=per_page,
            search=search,
            room_type_id=room_type_id,
            room_status_id=room_status_id
        )
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/rooms/<int:room_id>', methods=['GET'])
@jwt_required()
def get_room(room_id):
    """获取房间详情"""
    try:
        data = room_service.get_room_dto(room_id)
        if not data:
            return ApiResponse.error(msg='房间不存在', code=404)
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/rooms', methods=['POST'])
@jwt_required()
def create_room():
    """创建房间"""
    try:
        data = request.get_json()
        
        required_fields = ['roomNumber', 'floor', 'roomTypeId']
        for field in required_fields:
            if field not in data or not data[field]:
                return ApiResponse.error(msg=f'缺少必填字段: {field}', code=400)
        
        result = room_service.create_room_dto(
            room_number=data['roomNumber'],
            floor=data['floor'],
            room_type_id=data['roomTypeId'],
            area=data.get('area'),
            bed_type=data.get('bedType'),
            max_guests=data.get('maxGuests', 2),
            room_status_id=data.get('roomStatusId', 1),
            description=data.get('description')
        )
        
        return ApiResponse.success(data=result, msg='房间创建成功', code=201)
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/rooms/<int:room_id>', methods=['PUT'])
@jwt_required()
def update_room(room_id):
    """更新房间"""
    try:
        data = request.get_json() or {}
        
        update_data = {}
        field_mapping = {
            'roomNumber': 'room_number',
            'floor': 'floor',
            'roomTypeId': 'room_type_id',
            'area': 'area',
            'bedType': 'bed_type',
            'maxGuests': 'max_guests',
            'roomStatusId': 'room_status_id',
            'description': 'description'
        }
        
        for api_field, model_field in field_mapping.items():
            if api_field in data and data[api_field] is not None:
                update_data[model_field] = data[api_field]
        
        result = room_service.update_room_dto(room_id, **update_data)
        if not result:
            return ApiResponse.error(msg='房间不存在', code=404)
        
        return ApiResponse.success(data=result, msg='房间更新成功')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/rooms/<int:room_id>', methods=['DELETE'])
@jwt_required()
def delete_room(room_id):
    """删除房间"""
    try:
        result = room_service.delete_room(room_id)
        if not result:
            return ApiResponse.error(msg='房间不存在', code=404)
        
        return ApiResponse.success(msg='房间删除成功')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/room-types', methods=['GET'])
@jwt_required()
def get_room_types():
    """获取房间类型"""
    try:
        room_types = room_service.get_room_types()
        data = [{'id': rt.id, 'name': rt.name, 'basePrice': float(rt.base_price)} for rt in room_types]
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/room-statuses', methods=['GET'])
@jwt_required()
def get_room_statuses():
    """获取房间状态"""
    try:
        statuses = room_service.get_room_statuses()
        data = [{'id': s.id, 'name': s.name, 'colorCode': s.color_code} for s in statuses]
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/rooms/availability', methods=['POST'])
@jwt_required()
def check_availability():
    """检查房间可用性"""
    try:
        data = request.get_json()
        room_id = data.get('roomId')
        check_in = data.get('checkIn')
        check_out = data.get('checkOut')
        
        if not all([room_id, check_in, check_out]):
            return ApiResponse.error(msg='缺少必填字段', code=400)
        
        from datetime import datetime
        if isinstance(check_in, str):
            check_in = datetime.strptime(check_in, '%Y-%m-%d')
        if isinstance(check_out, str):
            check_out = datetime.strptime(check_out, '%Y-%m-%d')
        
        available = room_service.check_room_availability(room_id, check_in, check_out)
        return ApiResponse.success(data={'available': available})
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)

